import { Car, CarDocument } from '@app/database/schemas/car.schema';
import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Patch,
  Post,
  Req,
  UseGuards,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Model } from 'mongoose';

@ApiTags('前台购物车模块')
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
@Controller('cars')
export class CarsController {
  constructor(
    @InjectModel('Car')
    private readonly carModel: Model<CarDocument>,
  ) {}

  @ApiOperation({ summary: '购物车添加书籍' })
  @Post()
  async addCar(@Body() car: Car, @Req() request: any) {
    let res = await this.carModel.findOne({ order: car.order, book: car.book });
    if (res) {
      res.number += car.number;
      await res.save();
    } else {
      car.user = request.user._id;
      res = await this.carModel.create(car);
    }
    return res;
  }

  @ApiOperation({ summary: '购物车修改书籍数目' })
  @Patch(':id')
  async updateCar(@Param('id') id: string, @Body() car: Car) {
    return this.carModel.updateOne({ _id: id }, { number: car.number });
  }

  @ApiOperation({ summary: '购物车书籍列表' })
  @Get(':id')
  showCar(@Param('id') orderId: string, @Req() request: any) {
    return this.carModel
      .find({ order: orderId, user: request.user._id })
      .populate('book');
  }

  @ApiOperation({ summary: '购物车删除书籍' })
  @Delete(':id')
  deleteOne(@Param('id') id: string) {
    return this.carModel.deleteOne({ _id: id });
  }
}
